import axios, { AxiosError, AxiosRequestConfig, AxiosResponse, InternalAxiosRequestConfig } from 'axios'
// import { ElMessage } from 'element-plus';
import { AxiosType } from '@/http/types'

const service = axios.create({
  baseURL: import.meta.env.VITE_BASE_API,
  timeout: 15000,
  withCredentials: true,
  timeoutErrorMessage: '请求超时，请重试'
})
// axios实例拦截请求
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // header中添加值
    // config.headers['code'] = `Bearer ${localStorage.getItem('token')}`
    return {
      ...config
    }
  },
  (error: AxiosError) => {
    return Promise.reject(error)
  }
)
// axios实例拦截响应
service.interceptors.response.use(
  (response: AxiosResponse) => {
    const { data } = response
    switch (data.code) {
      case AxiosType.CodeType.SUCCESS:
        return response
      case AxiosType.CodeType.UNLOGIN:
        // ElMessage({
        //     message: '登录已过期，请重新登录',
        //     type: 'error',
        //     plain: true
        // });
        return Promise.reject(response)
      default:
        // ElMessage({
        //     message: data.message,
        //     type: 'error'
        // });
        return Promise.reject(response)
    }
  },
  // 请求失败
  (error: any) => {
    // ElMessage({
    //     message: '网络连接异常,请稍后再试!',
    //     type: 'error'
    // });
    return Promise.reject(error)
  }
)

// 此处相当于二次响应拦截
// 为响应数据进行定制化处理
const requestInstance = <T = any>(config: AxiosRequestConfig): Promise<T> => {
  const conf = config
  return new Promise((resolve, reject) => {
    service
      .request<any, AxiosResponse<AxiosType.BaseResponse>>(conf)
      .then((res: AxiosResponse<AxiosType.BaseResponse>) => {
        const data = res.data
        // 如果data.code为错误代码返回message信息
        if (data.code !== AxiosType.CodeType.SUCCESS) {
          // ElMessage({
          //     message: data.message,
          //     type: 'error'
          // });
          reject(data.message)
        } else {
          // 成功的时候 此处返回data信息 也就是 api 中配置好的 Response 类型
          resolve(data as T)
        }
      })
  })
}

export default {
  get<T = any, U = any>(url: string, params?: U, config: AxiosRequestConfig = {}): Promise<AxiosType.BaseResponse<T>> {
    return requestInstance({ ...config, url, method: 'GET', params: params })
  },
  post<T = any, U = any>(url: string, data?: U, config: AxiosRequestConfig = {}): Promise<AxiosType.BaseResponse<T>> {
    return requestInstance({ ...config, url, method: 'POST', data })
  },
  put<T = any, U = any>(url: string, params?: U, config: AxiosRequestConfig = {}): Promise<AxiosType.BaseResponse<T>> {
    return requestInstance({ ...config, url, method: 'PUT', params: params })
  },
  del<T = any, U = any>(url: string, data?: U, config: AxiosRequestConfig = {}): Promise<AxiosType.BaseResponse<T>> {
    return requestInstance({ ...config, url, method: 'DELETE', data })
  }
}
// 用法
// import request from '@/http/request';
// export const getAuthListApi = async () => {
//   return request.get<ts类型>('authList');
// };
